using System;
using System.Collections.Generic;
using UnityEngine;
using Voodoo.Sauce.Internal.CrossPromo.Mobile;
using Voodoo.Sauce.Internal.CrossPromo.Models;
using Voodoo.Sauce.Internal.CrossPromo.Utils;

namespace Voodoo.Sauce.Internal.CrossPromo
{
	internal class CrossPromoInfo
	{
		public bool HasInternet;

		public GameModel CurrentGame
		{
			get;
			set;
		}

		public List<AssetModel> Assets
		{
			get;
			private set;
		}

		public List<AssetModel> Waterfall
		{
			get;
			private set;
		}

		public List<AssetModel> GamesInstalled
		{
			get;
			private set;
		}

		public bool CrossPromoIsReady
		{
			get;
			set;
		}

		public string Format
		{
			get;
			set;
		}

		public CrossPromoInfo()
		{
			CurrentGame = null;
			Assets = new List<AssetModel>();
			Waterfall = new List<AssetModel>();
			GamesInstalled = new List<AssetModel>();
		}

		public bool GetInternetStatus()
		{
			return !HasInternet || Application.internetReachability == NetworkReachability.NotReachable;
		}

		public void FilterAssets()
		{
			Assets.Clear();
			AssetModel[] promote_assets = CurrentGame.promote_assets;
			foreach (AssetModel assetModel in promote_assets)
			{
				if (MobileCrossPromoWrapper.IsAppInstalled(assetModel.game))
				{
					GamesInstalled.Add(assetModel);
				}
				else
				{
					Assets.Add(assetModel);
				}
			}
		}

		public void FillAssetsListFromCache()
		{
			Assets.Clear();
			string[] allFilesFromCache = CacheManager.GetAllFilesFromCache();
			foreach (string filePath in allFilesFromCache)
			{
				try
				{
					string @string = PlayerPrefs.GetString(PlayerPrefsUtils.GetKey(filePath));
					if (string.IsNullOrEmpty(@string))
					{
						throw new Exception();
					}
					AssetModel item = JsonUtility.FromJson<AssetModel>(@string);
					Assets.Add(item);
				}
				catch (Exception)
				{
					CacheManager.DeleteFile(filePath);
				}
			}
			Shuffle(Assets);
		}

		private static void Shuffle<T>(IList<T> list)
		{
			System.Random random = new System.Random();
			int num = list.Count;
			while (num > 1)
			{
				num--;
				int index = random.Next(num + 1);
				T value = list[index];
				list[index] = list[num];
				list[num] = value;
			}
		}
	}
}
